<%@ page language="java" contentType="text/html;charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page import="com.webside.points.wechat.Constant"%> 
<%
	String issueTypeId = request.getParameter("issueTypeId");

	String issueId = request.getParameter("issueId");
	request.setAttribute("issueId", issueId);
	
	String expert = request.getParameter("expert");
	request.setAttribute("expert", expert);

	String openId = request.getParameter("openId");
	request.getSession().setAttribute("openId", openId);

	String type = request.getParameter("type");
	request.setAttribute("type", type);
	
	HttpSession httpSession=request.getSession();
	
	httpSession.setMaxInactiveInterval(-1); 
	httpSession.setAttribute("userName", "Wechat");
	
	String url = Constant.REALM_URL;

%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
	content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="stylesheet" href="../css/amazeui.min.css">
<link rel="stylesheet" href="../css/wap.css">
<link rel="stylesheet" href="../css/style.css" />
<link rel="stylesheet" href="../css/weui.css" />
<link rel="stylesheet" href="../css/record.css" />
<link rel="stylesheet" href="../css/tab.css" />
<title>提问</title>
<script src="../js/jquery.js"></script>
<script src="../js/amazeui.min.js"></script>
  <script type="text/javascript"
	src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">

	$(function(){
		//异步展示问题内容
		var issueId=$("#issueId").val();
		if(issueId!=null){
			var url = "${ctx }/issue/findByIssueId";
			var params = {"issueId":issueId};
			$.post(url, params, function(data, status, xhr){
				callbackConfig(data);
			},'json');
			
			function callbackConfig(data){
				console.log($("#showIssue").text());
				$("#showIssue").text(data.issueContent);
			}
		}
		
		
		var issueType = $(".weui-cells_checkbox");
		//alert(issueType);
		if(issueType!=null){
			var url = "${ctx }/issueType/findIssueType";
			
			$.post(url, function(data, status, xhr){
				callback(data);
			},'json');
			
			function callback(data){
				var html ="";
				for(var i=0;i<data.length;i++){
					if(data[i].status==1){
						
						if(i==0){
							html +='<label class="weui-check__label" style="font-weight: normal;width:33%;font-size:1.4rem;">'
								+'<div class="weui-cell__hd">'
									+'<input type="radio" name="issueTypeId" class="weui-check" value="'+data[i].id+'" checked="checked"/>'
									+'<i class="weui-icon-checked"></i>'
									+' '+data[i].issueTypeName+''
								+'</div>'
							+'</label>'
						}else{
							html +='<label class="weui-check__label" style="font-weight: normal;width:33%;font-size:1.4rem;">'
								+'<div class="weui-cell__hd">'
									+'<input type="radio" name="issueTypeId" class="weui-check" value="'+data[i].id+'"/>'
									+'<i class="weui-icon-checked"></i>'
									+' '+data[i].issueTypeName+''
								+'</div>'
							+'</label>'
						}
					}
				}
				$(issueType).prepend(html);
				
			}
		}
		
		
	});

	$(document).ready(
		function(e) {
			$(".tab li").click(
				function() {
					$(".tab li").eq($(this).index()).addClass("activ")
								.siblings().removeClass("activ");
					$(".tabCon div").hide().eq($(this).index()).show();
					$(".weui-textarea").text("");
					del();
					$("#uploaderFiles").html("");
			});
	});
	$(function() {
		if ("${type}" == "answer") {
			$("#form")[0].action = "${ctx }/answer/insert";
		}
	})
	function checkSize(param) {
		var size = param.value.length;
		if (size == 99) {
			param.setAttribute("onkeypress", "javascript:return false");
		} else if (size <= 99) {
			param.setAttribute("onkeypress", "");
		}
	}
</script>

<script type="text/javascript">
	var localId;
	var recordTime=0;
	var playTime=0;
	var interval;
	var serverId;
	var imgLocalId;
	var imgServerId;
	var imgData="";
	
	function wxConfig(){
		
		var url = "${ctx }/wechat/getWxSignatureByTicket";
		
		var href=window.location.href;
		var params = {"url":href};
		   
		$.post(url, params, function(data, status, xhr){
			callbackConfig(data);
		},'json');
	}
	wxConfig();
	function callbackConfig(data) {
		 wx.config({
		      debug: false,
		      appId: data.appId,
		      timestamp: data.timestamp,
		      nonceStr: data.noncestr,
		      signature: data.signature,  
		      jsApiList: [
				'checkJsApi',
				'startRecord',
		        'stopRecord',
		        'playVoice',
		        'stopVoice',
		        'uploadVoice',
		        'downloadVoice',
				'chooseImage',
				'uploadImage',
				'downloadImage',
				'getLocalImgData',
				'hideMenuItems',
		      ]
		  }); 
	}
	
	//检查接口是否能调用
	wx.ready(function () {
		wx.checkJsApi({
		    jsApiList: [
		        'startRecord',
		        'stopRecord',
		        'pauseVoice'
		    ],
		    success: function (res) {
		        // alert(JSON.stringify(res));
		        // alert(JSON.stringify(res.checkResult.getLocation));
		        if (res.checkResult.getLocation == false) {
		            alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
		            return;
		        }
		    }
		});
		//分享图片路径
		var url = "<%=url%>" +"images/share.jpg";
		
		//alert(url);
		
		//分享给朋友圈
		wx.onMenuShareTimeline({
			title: '欢迎使用中穆问答', // 分享标题
			link: "<%=url%>" , // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: url, // 分享图标
			success: function () { 
				// 用户确认分享后执行的回调函数
			},
			cancel: function () { 
				// 用户取消分享后执行的回调函数
			}
		});
		//分享给朋友
		wx.onMenuShareAppMessage({
			title: '欢迎使用中穆问答', // 分享标题
			desc: '穆斯林的问题，来问中穆问答。这里有许多专家随时为您答疑解惑。', // 分享描述
			link: "<%=url%>", // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
			imgUrl: url, // 分享图标
			success: function () { 
				// 用户确认分享后执行的回调函数
			},
			cancel: function () { 
				// 用户取消分享后执行的回调函数
			}
		});
	});
	//开始录音
	function startRecord(){
		$("#record").html("<span class='button-stop-record'></span>");
		//
		$("#record").attr('onclick','stopRecord()');
		wx.startRecord();
		interval = setInterval(a, 1000);
		function a(){
			recordTime=recordTime+1;
			$(".time-big").text(formatTime(recordTime));
			if(recordTime==60){
				stopRecord();
			}
		}
	}
	
	//停止录音
	function stopRecord(){
		var $loadingToast = $('#loadingToast');
		if ($loadingToast.css('display') != 'none') return;
		$loadingToast.fadeIn(100);
		wx.stopRecord({
		    success: function (res) {
		    	localId = res.localId;
		    	clearInterval(interval);
		    	$("#record").attr('onclick','playVoice()');
		    	$("#record").html("<img class='image' src='../images/play.png'></img>");
		    	$("#del").html("<img class='image' src='../images/trash.png'></img>");
		    	$(".time-big").text(formatTime(playTime));
		    	$(".page-body-time").append("<span class='time-small'>"+formatTime(recordTime)+"</span>");
				 $(".weui-textarea").text(serverId+"-"+recordTime);
		    	//uploadVoice();
				 $loadingToast.fadeOut(100);
		    }
		});
	}
	//删除录音
	function del(){
		$("#record").attr('onclick','startRecord()');
		$("#record").html("<img class='image' src='../images/record.png'></img>");
		$(".time-small").remove();
		$("#del").html("");
		$(".weui-textarea").text("");
		localId=null;
		recordTime=0;
		playTime=0;
		$(".time-big").text(formatTime(recordTime));
		$(".time-big").text(formatTime(playTime));
		clearInterval(interval);
	};
	
	//播放录音
	function playVoice(){
		//alert(localId);
		wx.playVoice({
		    localId: localId // 需要播放的音频的本地ID，由stopRecord接口获得
		});
		$("#record").attr('onclick','stopVoice()');
		$("#record").html("<img class='image' src='../images/stop.png'></img>");
		interval = setInterval(b, 1000);
		function b(){
			playTime=playTime+1;
			$(".time-big").text(formatTime(playTime));
			if(playTime==recordTime){
				stopVoice();
			}
		}
	}
	
	//停止播放
	function stopVoice(){
		wx.stopVoice({
		    localId: localId // 需要停止的音频的本地ID，由stopRecord接口获得
		});
		clearInterval(interval);
		$("#record").attr('onclick','playVoice()');
		$("#record").html("<img class='image' src='../images/play.png'></img>");
		playTime=0;
		$(".time-big").text(formatTime(playTime));
	}
	
	//上传语音
	function uploadVoice(){
		wx.uploadVoice({
		    localId: localId, // 需要上传的音频的本地ID，由stopRecord接口获得
		    isShowProgressTips: 1, // 默认为1，显示进度提示
		        success: function (res) {
		        serverId = res.serverId; // 返回音频的服务器端ID
		        downloadVoice();
		    }
		});
	}
	
	//下载语音
	function downloadVoice(){
		wx.downloadVoice({
		    serverId: serverId, // 需要下载的音频的服务器端ID，由uploadVoice接口获得
		    isShowProgressTips: 1, // 默认为1，显示进度提示
		    success: function (res) {
		        localId = res.localId; // 返回音频的本地ID
		        $(".weui-textarea").text(serverId+"-"+recordTime);
		        //alert(localId);
		    }
		});
	}
	//时间格式化（比如：60---->00:01:00）
	function formatTime(time) {
		  if (typeof time !== 'number' || time < 0) {
			return time
		  }
		  var hour = parseInt(time / 3600)
		  time = time % 3600
		  var minute = parseInt(time / 60)
		  time = time % 60
		  var second = time
		  return ([hour, minute, second]).map(function (n) {
			n = n.toString()
			return n[1] ? n : '0' + n
		  }).join(':')
		}
	//选择图片与拍照	
	function chooseImage(){
		//删除已有的照片
		$("#uploaderFiles").html("");
		wx.chooseImage({
			count: 9, // 默认9
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
			success: function (res) {

				imgLocalId = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片

					//上传图片
					var count=0;
					var maxCount=imgLocalId.length;
					function uploadImage(){
						//alert(imgLocalId.length);						
								
								var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)" id="#value#"><span class="weui-icon-cancel" style="float:right;font-size:18px;" onclick="remove(this)"></span> </li>';
								 if (window.__wxjs_is_wkwebview) {
									//ios
										tmpl=tmpl.replace("#value#", imgLocalId[count]);
										wx.getLocalImgData({
											localId: imgLocalId[count], // 图片的localID
											success: function (res) {
												var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
												localData = localData.replace('jgp', 'jpeg');
												//alert(localData);
												
												tmpl=tmpl.replace("#url#", localData);
												//alert(imgLocalId[count]);
												
												//alert(tmpl);
												
												$("#uploaderFiles").append(tmpl);
											}
										});
									 
								 }else{
									 //安卓
									 tmpl=tmpl.replace("#url#", imgLocalId[count]);
									 tmpl=tmpl.replace("#value#", imgLocalId[count]);
									 $("#uploaderFiles").append(tmpl);
								 }
								
								count++;
								if(maxCount>count){
									uploadImage();
								}
								
							}
							
				uploadImage();
			}
		});
	}
	//上传到服务器
	$(function(){
		var $tooltips = $('.js_tooltips');
		
		$(".weui-btn_primary").click(function(){
			//alert(1);
			var $loadingToast=null;
				
			   var li =$("#uploaderFiles li");
			  // alert(li.length);
			   
			   var value=$(".weui-textarea").val();
			   
			   
			   if(value!=""){
				   //开始加载
					$loadingToast = $('#loadingToast');
					if ($loadingToast.css('display') != 'none') return;
					$loadingToast.fadeIn(100);
				   var count=0;
				   var maxCount=li.length;
				   
				   function image(){
					   
					   //alert(li[count].id);
					   var id=$(li[count]).attr("id");
					   //alert(id);
					   wx.uploadImage({
						localId: id, // 需要上传的图片的本地ID，由chooseImage接口获得
						isShowProgressTips: 1, // 默认为1，显示进度提示
						success: function (res) {		 
							
							var serverId = res.serverId; // 返回图片的服务器端ID
							//alert(serverId);
							
							var url = "${ctx}/wechat/mediaGet";
							//alert(url);
							
							$.ajax({ 
							   type: "post", 
							   url: url, 
							   async:false, 
							   data:"mediaId="+serverId+"&savePath=upload",
							   success: function(data){ 
							     // alert(data);
								  imgData = imgData+";"+data;
							   } 
							});
							 count++;
								if(count<maxCount){
									image();
								}else{
									//alert(imgData);
									$("#image").val(imgData);
									$loadingToast.fadeOut(100);
									 $("#form").submit();
								}
						}
					});
					   
				   }
				   
				    if(li.length!=0){
					    image();
				   }else{
					   uploadVoice($loadingToast);
				   }
				   
				   
			   }else{
				   out("请输入问题内容");
			   }
			  
		})
		
		function out(content){
			$($tooltips).text(content)
					
			if ($tooltips.css('display') != 'none') return;
			// toptips的fixed, 如果有`animation`, `position: fixed`不生效
			$('.page.cell').removeClass('slideIn');
			$tooltips.css('display', 'block');
			setTimeout(function () {
				$tooltips.css('display', 'none');
			}, 2000);
		}
	});
	
	function uploadVoice($loadingToast){
		//alert(1);
		 if(localId!=null){
		   //alert(localId);
		   wx.uploadVoice({
				localId: localId, // 需要上传的音频的本地ID，由stopRecord接口获得
				isShowProgressTips: 1, // 默认为1，显示进度提示
					success: function (res) {
						
					serverId = res.serverId; // 返回音频的服务器端ID
					//alert(serverId);
					console.log(serverId);
					
					var url = "${ctx}/wechat/mediaGet";
				//alert(url);
					$.ajax({ 
					   type: "post", 
					   url: url, 
					   async:false, 
					   data:"mediaId="+serverId+"&savePath=upload",
					   success: function(data){ 
						  //alert(data);
						   $(".weui-textarea").text(data+";"+recordTime);
						   
						   $loadingToast.fadeOut(100);
						   
						   $("#form").submit();
					   } 
					});
					
				}
			}); 
	   }else{
		   $loadingToast.fadeOut(100);
		   $("#form").submit();
	   }
	}

	
	//删除
	function remove(e){
		$(e).parent().remove();
	}
	
	$(function(){
		
		
		var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>',
			$gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
			$uploaderInput = $("#uploaderInput"),
			$uploaderFiles = $("#uploaderFiles")
			;

		$uploaderInput.on("change", function(e){
			var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
			for (var i = 0, len = files.length; i < len; ++i) {
				var file = files[i];
				if (url) {
					src = url.createObjectURL(file);
					
				} else {
					src = e.target.result;
				}

				$uploaderFiles.append($(tmpl.replace('#url#', src)));
			}

		});
		
	});
	
	function delImage(){
		$(".page").css("display","none");
	}
	
	function addImage(){
		$(".page").css("display","block");
	}

	</script>
</head>
<body style="background: #ececec">
<!--错误提示-->
<div class="weui-toptips weui-toptips_warn js_tooltips"></div>

    <!-- loading toast -->
    <div id="loadingToast" style="display:none;">
		<div class="weui-mask_transparent"></div>
		<div class="weui-toast">
			<i class="weui-loading weui-icon_toast"></i>
			<p class="weui-toast__content">数据加载中</p>
		</div>
	</div>

	<div class="pet_mian">
		<div class="pet_content pet_content_list pet_hd">
			<div class="pet_article_like">
				<div class="pet_content_main pet_article_like_delete">
					<div data-am-widget="list_news"
						class="am-list-news am-list-news-default am-no-layout">
						<div class="am-list-news-bd">
							<c:if test="${type!='issue' }">
								<span>
									<b>问题内容：</b><font id="showIssue"></font>
								</span>
							</c:if>
							<form action="${ctx }/issue/insert" method="post" id="form">
								<!-- 选项卡 -->
								<div class="table_card">
									<ul class="tab">
										<li class="activ" onclick="addImage()">文字</li>
										<c:if test="${type == 'answer'}">
										<li onclick="delImage()">语音</li>
										</c:if>
									</ul>
									<div class="tabCon">
									
										<div class="on">
											<input type="hidden" name="image" id="image" >
											<c:if test="${expert!=null}">
												<input type="hidden" name="expert" value="${expert}" >
											</c:if>
											
											<c:if test="${type != 'issue'}">
												<input type="hidden" name="id" value="<%=issueId%>" id="issueId">
											</c:if>
											<input type="hidden" name="openId" value="<%=openId%>" id="openId">
											<textarea class="weui-textarea" required placeholder="请输入文字" rows="8" name="issueContent" onkeydown="checkSize(this)"></textarea>
											
											
										</div>
										<c:if test="${type == 'answer'}">
										<div>
											<span class="page-body-time">
									          <span class="time-big">00:00:00</span>
									        </span>
									        <span class="page-body-buttons" style="margin-bottom:80px;">
									          <span class="page-body-button"></span>
									          <span class="page-body-button" id="record" onclick="startRecord()">
									            <img class="image" src="../images/record.png"></img>
									          </span>
									          <span class="page-body-button" id="del" onclick="del()">
									          </span>
											  </span>
											  
											  <span style="color:red;font-size:1.5rem;">注：点击话筒开始录音，录音完毕之后可以试听、删除、重新录音。录音限制为一分钟！</span>
											 
										</div>
										</c:if>
									</div>
									
									<div class="page" >
										<div class="page__bd">
											<div class="weui-cells weui-cells_form" style="margin-top:0px;">
												<div style="padding: 10px 15px;">
													<div class="weui-cell__bd">
														<div class="weui-uploader">
															<div class="weui-uploader__bd">
																<ul class="weui-uploader__files" id="uploaderFiles">
																	
																</ul>
																<div class="weui-uploader__input-box">
																	<input type="button" id="uploaderInput" class="weui-uploader__input" onclick="chooseImage()"/>
																</div>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
									<c:if test="${type == 'issue'}">
									
									 <div class="weui-cells_checkbox" style="margin:10px 7px;padding:0px;display: flex;align-items: center;">		
			
										<div style="font-weight: normal;width:33%;font-size:1.4rem;padding:0px;float:right;display: flex;align-items: center;">
											<span style="padding-right:8px;">匿名</span>
											<div class="weui-cell__ft" style="display:inline-block;">
												<label for="switchCP" class="weui-switch-cp">
													<input class="weui-switch" type="checkbox" name="anonymity" style="float:right"/>
												</label>
											</div>
										</div>
										
									</div>
									</c:if>
								</div>
								<br />
								<div class="button-sp-area" style="margin-bottom:20%;">
									<c:if test="${type == 'issue'}">
										<input type="button" class="weui-btn weui-btn_primary"
											value="提问" >
									</c:if>
									<c:if test="${type == 'answer'}">
										<input type="button" class="weui-btn weui-btn_primary"
											value="回答" >
									</c:if>
								</div>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!--底部-->
		<div data-am-widget="navbar" class="am-navbar am-cf my-nav-footer "
			id="">
			<ul class="am-navbar-nav am-cf am-avg-sm-4 my-footer-ul">
			<li>
			   <a href="${ctx }/user/findUserIssue?issueTypeId=0" class="">
				<span class="am-icon-home"></span>
				<span class="am-navbar-label">首页</span>
			  </a>
			</li>
			<li>
			  <a href="${ctx }/issueType/findAll?mark=service&openId=<%=openId %>" class="">
				<span class="am-icon-comments"></span>
				<span class="am-navbar-label">提问</span>
			  </a>
			</li>
			<li>
			  <a href="${ctx }/postType/findAllPostType" class="">
				<span class="am-icon-book"></span>
				<span class="am-navbar-label">学习</span>
			  </a>
			</li>
			<li style="position:relative">
			  <a href="${ctx }/user/findByOpenId?openId=<%=openId %>" class="">
				<span class="am-icon-user"></span>
				<span class="am-navbar-label">我的</span>
			  </a>
			</li>
		  </ul>
		</div>
	</div>
  <script src="../js/text-calculation.js"></script>
   <script>
	$(function(){
		$(".tab li").attr("style", "");
	})
  </script>
</body>
</html>